package com.leetcode.bfs_dfs;

import com.leetcode.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/*
    问题描述：
    给定一个二叉树，找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
    说明：叶子节点是指没有子节点的节点。
 */
public class Leetcode111 {
    /* solution 1: 广度优先搜索(BFS)
     */
    /*
    public int minDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        int level = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            level ++;
            int levelSize = queue.size();
            for(int i=0; i<levelSize; i++){
                TreeNode curr = queue.poll();
                if(curr.left == null && curr.right ==null){
                    return level;
                }

                if(curr.left != null){
                    queue.offer(curr.left);
                }
                if(curr.right != null){
                    queue.offer(curr.right);
                }
            }
        }

        return level;
    }
*/
    //solution 2: 深度优先搜索，参考Leetcode104
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        //特殊情况，如果当前节点的左孩子是null，而右孩子不是空，那么它就不能算是叶子节点
        //特殊例子如：root节点和一个右孩子节点，左节点是null
        if(root.left == null){
            return 1+minDepth(root.right);
        }

        if(root.right == null){
            return 1+minDepth(root.left);
        }

        int left = minDepth(root.left);
        int right = minDepth(root.right);

        return Math.min(left,right)+1;
    }


    /**
     *  测试程序
     *     3
     *    / \
     *   9  20
     *     /  \
     *    15   7
     * @param args
     */
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        TreeNode left = new TreeNode(9);
        TreeNode right = new TreeNode(20);
        root.left = left;
        root.right = right;
        TreeNode rleft = new TreeNode(15);
        TreeNode rright = new TreeNode(7);
        right.left = rleft;
        right.right = rright;

        Leetcode111 leetcode111 = new Leetcode111();
        System.out.println(leetcode111.minDepth(root));
    }
}